package com.hk.Mgr.web.controller.product;

import java.io.IOException;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hk.Mgr.web.message.order.AllAssetsRes;
import com.hk.app.utils.RedisCilent;
import com.hk.base.ResponseBase;
import com.hk.commons.HqlFilter;
import com.hk.commons.ResultCode;
import com.hk.commons.StringHelper;
import com.hk.commons.entity.order.OrderInfo;
import com.hk.commons.entity.order.OrderRouteInfo;
import com.hk.commons.entity.product.ProductInfo;
import com.hk.commons.entity.sys.SysUser;
import com.hk.commons.entity.yingmi.FundNav;
import com.hk.commons.entity.yingmi.YingmiDayProfit;
import com.hk.commons.utils.sys.DateWeekOrHoliday;
import com.hk.commons.utils.yingmi.YingmiApiUtils;
import com.hk.service.IFundNav;
import com.hk.service.order.IOrderInfo;
import com.hk.service.order.IOrderRouteInfo;
import com.hk.service.product.IProductInfo;
import com.hk.service.product.IProductRouteInfo;
import com.hk.service.sys.ISysUser;

@Controller
public class QueryDayProfitsController implements Serializable {

	private static final long serialVersionUID = 1397526057787898289L;

	private Logger logger = LoggerFactory
			.getLogger(QueryDayProfitsController.class);
	@Autowired
	private ISysUser sysUserService;// 用户信息

	@Autowired
	private IOrderRouteInfo orderRouteInfoService;// 订单路由信息

	@Autowired
	private IOrderInfo orderInfoService;// 订单确认信息

	@Autowired
	private IFundNav fundNavService;

	@Autowired
	private IProductRouteInfo proRouteService;

	@Autowired
	private IProductInfo productInfoService;

	@Autowired
	private YingmiApiUtils utils;

	@ResponseBody
	@RequestMapping(value = "/qryAllAssets", produces = "application/json;charset=UTF8", method = RequestMethod.GET)
	public ResponseBase<List<AllAssetsRes>> qryAllAssets(
			@RequestParam String userId) {
		userId = userId.split(",")[0];
		ResponseBase<List<AllAssetsRes>> responseBase = new ResponseBase<List<AllAssetsRes>>();
		List<AllAssetsRes> resAllAssetsList = new ArrayList<AllAssetsRes>();
		// 通过用户id查询路由表
		SysUser user = null;
		if (RedisCilent.existsKey("ALL_ASSETS_yingmiFundsList" + userId)) {
			RedisCilent.delKey("ALL_ASSETS_yingmiFundsList" + userId);
		}
		if (RedisCilent.existsKey("ALLASSETS_wayOrderStr" + userId)) {
			RedisCilent.delKey("ALLASSETS_wayOrderStr" + userId);
		}
		if (RedisCilent.existsKey("ALLASSETS_gudingProduct" + userId)) {
			RedisCilent.delKey("ALLASSETS_gudingProduct" + userId);
		}
		if (RedisCilent.existsKey("ALLASSETS_yingmibao" + userId)) {
			RedisCilent.delKey("ALLASSETS_yingmibao" + userId);
		}

		List<SysUser> users = qryUser(userId);
		String msg;
		String resultCode;

		if (users.size() > 0) {
			AllAssetsRes jjLicai = new AllAssetsRes();
			AllAssetsRes yingmiWayOrder = new AllAssetsRes();
			AllAssetsRes gdShouyi = new AllAssetsRes();
			AllAssetsRes ymb = new AllAssetsRes();
			user = users.get(0);
			try {
				getHuoChaiAndOur(user, gdShouyi);
			} catch (Exception e) {
				logger.error("固定资产获取异常！userId={}", userId);
			}
			resAllAssetsList.add(gdShouyi);
			if ((!StringHelper.isEmpty(user.getAccountId()) && (!StringHelper
					.isEmpty(user.getName())))) {
				try {
					getymFunds(user, jjLicai);
				} catch (Exception e) {
					logger.error("获取盈米基金异常！userId={}", userId);
				}
				try {
					getWayOrder(user, yingmiWayOrder);
				} catch (Exception e) {
					logger.error("获取在途资产异常！userId={}", userId);
				}
				try {
					getYMB(user, ymb);
				} catch (Exception e) {
					logger.error("获取盈米宝异常！userId={}", userId);
				}
				resAllAssetsList.add(jjLicai);
				resAllAssetsList.add(yingmiWayOrder);
				resAllAssetsList.add(ymb);
				msg = "成功";
				resultCode = ResultCode.SUCC.getCode();
			} else {
				logger.info(
						"客户accountId为空或手机号为空，无法查询基金相关。accountId={},name={}",
						user.getAccountId(), user.getName());
				msg = "客户账户Id为空或手机号为空，无法查询基金";
				resultCode = ResultCode.FAILED.getCode();
				// resAllAssetsList = null;
			}
		} else {
			msg = "查询不到客户";
			resultCode = ResultCode.FAILED.getCode();
		}
		responseBase.setMsg(msg);
		responseBase.setResultCode(resultCode);
		responseBase.setResult(resAllAssetsList);
		return responseBase;

	}

	private void getWayOrder(SysUser user, AllAssetsRes yingmiWayOrder)
			throws ClientProtocolException, IOException {
		// 获取在途基金订单 /trade/getProcessingFundOrders
		Map<String, String> paramorder = new HashMap<>();
		paramorder.put("brokerUserId", user.getName());
		paramorder.put("accountId", user.getAccountId());
		String moniZaituOrder = utils.get("/trade/getProcessingFundOrders",
				paramorder);
		if (!moniZaituOrder.contains("msg")) {
			RedisCilent.setString("ALLASSETS_wayOrderStr" + user.getId(),
					moniZaituOrder, 1000);
			JSONArray array = new JSONArray(moniZaituOrder);
			BigDecimal wayAllMoney = new BigDecimal(0.0);
			if (array.length() > 0) {
				for (int i = 0; i < array.length(); i++) {
					JSONObject object = array.getJSONObject(i);
					int payStatus = Integer.valueOf((String) object
							.get("payStatus"));
					if (payStatus == 2) {// 扣款成功
						BigDecimal orderMoney = new BigDecimal(object.get(
								"tradeAmount").toString());
						wayAllMoney = wayAllMoney.add(orderMoney);
					}
				}
				yingmiWayOrder.setFundsName("在途资产");
				yingmiWayOrder.setFundsNum(String.valueOf(array.length()));
				yingmiWayOrder.setFundsAllMoney(String.valueOf(wayAllMoney));
				// yingmiWayOrder.setOwnMoney(String.valueOf(wayAllMoney));
			}
		} else {
			yingmiWayOrder.setFundsName("在途资产获取失败");
		}
	}

	/* 查询固定收益类产品：火柴和自有产品 */
	private void getHuoChaiAndOur(SysUser user, AllAssetsRes gdShouyi) {
		// 通过路由表去订单确认表查询订单。
		HqlFilter routeHqlFilter = new HqlFilter();
		routeHqlFilter.addEQFilter("userId", user.getId());
		JSONArray allGdShouyiObj = new JSONArray();
	BigDecimal allMoney = new BigDecimal(0);
		List<OrderRouteInfo> userOrderRouteList = orderRouteInfoService
				.findByFilter(routeHqlFilter);
		if (userOrderRouteList.size() > 0) {
			int num = 0;
			BigDecimal gdAllMoney = new BigDecimal(0);
			BigDecimal gdljProfit = new BigDecimal(0);
			BigDecimal newProfit = new BigDecimal(0);

			for (OrderRouteInfo orderRouteInfo : userOrderRouteList) {
				int companyId = orderRouteInfo.getCompanyId();
				if (companyId == 3 || companyId == 1) {// 盈米4 火柴3 中融信通2 自己1
					Long orderId = orderRouteInfo.getOrderId();
					HqlFilter orderInfoFilter = new HqlFilter();
					orderInfoFilter.addEQFilter("id", orderId);
					List<OrderInfo> orderInfoList = orderInfoService
							.findByFilter(orderInfoFilter);
					if (orderInfoList.size() > 0) {
						BigDecimal nowProfit;
						for (OrderInfo orderInfo : orderInfoList) {
							if (orderInfo.getPayStatus() == 2) {// -----------------------2：已打款
																// 3:待确认
																// 4:还本付息中------------------------
								num++;
								BigDecimal benjin = orderInfo
										.getSuccessAmount();
								gdAllMoney = gdAllMoney.add(benjin);
								Date profitDate;
								if (orderInfo.getOrderTradeDate() != null) {
									profitDate = new Date(
											orderInfo.getOrderTradeDate());
									Calendar profitC = Calendar.getInstance();
									profitC.setTime(profitDate);
									Calendar nowTime = Calendar.getInstance();
									if (DateWeekOrHoliday.ifLongger(profitC,
											nowTime)) {
										logger.info(
												"YesterDayProfitCtrl->getHuoChaiAndOur未开始计息,orderId={}",
												orderId);
									} else {// 计息时间在今天之前则已经开始产生收益
										Date finalDate = new Date(
												orderInfo.getDividendDate());
										Calendar finalCalendar = Calendar
												.getInstance();
										finalCalendar.setTime(finalDate);
										Long productId = orderInfo
												.getProductId();
										String productName = qryProductName(
												productId, companyId);
										if (DateWeekOrHoliday.ifLongger(
												finalCalendar, nowTime)
												|| DateWeekOrHoliday.afterDay(
														finalCalendar, nowTime)) {
											// 未到还本付息时间则计算收益
											Calendar nowTimea = Calendar
													.getInstance();
											nowTimea.set(
													nowTime.get(Calendar.YEAR),
													nowTime.get(Calendar.MONTH),
													nowTime.get(Calendar.DAY_OF_MONTH));
											Calendar profitDatea = Calendar
													.getInstance();
											profitDatea
													.set(profitC
															.get(Calendar.YEAR),
															profitC.get(Calendar.MONTH),
															profitC.get(Calendar.DAY_OF_MONTH));
											Long nowDaysLong = (nowTimea
													.getTimeInMillis() - profitDatea
													.getTimeInMillis())
													/ (24 * 60 * 60 * 1000);
											BigDecimal yetDays = BigDecimal
													.valueOf(Math.abs(nowDaysLong
															.intValue()));// 算今天之前
											HqlFilter hqlFilter = new HqlFilter();
											hqlFilter.addEQFilter("Id",
													productId);
											List<ProductInfo> productList = productInfoService
													.findByFilter(hqlFilter);
											if (productList.size() > 0) {
												ProductInfo productInfo = productList
														.get(0);
												int days = productInfo
														.getProTerm();
												BigDecimal dividend = orderInfo
														.getDividend();
												BigDecimal dayProfit = dividend
														.divide(new BigDecimal(
																days), 5);
												nowProfit = yetDays
														.multiply(dayProfit);// 当前总收益：天数乘以利率
												allMoney = allMoney
														.add(nowProfit);
												gdAllMoney = gdAllMoney
														.add(nowProfit);
												gdljProfit = gdljProfit
														.add(nowProfit); // 全部产品相加
												newProfit = newProfit
														.add(dayProfit);
											} else {
												logger.info(
														"YesterDayProfitCtrl->getHuoChaiAndOur查询不到产品!productId={}",
														productId);
											}
										}
										JSONObject currentObj = new JSONObject();
										currentObj.put("date",
												orderInfo.getOrderTradeDate());
										currentObj.put("ProductName",
												productName);
										currentObj.put("touziAmout", benjin);
										currentObj.put("yuqiShouyi",
												orderInfo.getDividend());
										allGdShouyiObj.put(currentObj);
									}
								} else {
									logger.info(
											"YesterDayProfitCtrl->getHuoChaiAndOur未开始计息,orderId={}",
											orderId);
								}

							}
						}
					} else {
						// logger.info(
						// "QueryDayProfitsController->getHuoChaiAndOur订单确认表查询不到订单!accountId={},orderId={},",
						// user.getAccountId(), orderId);
					}
				}
			}
			gdShouyi.setNewProfit(String.valueOf(newProfit));
			gdShouyi.setFundsName("理财产品");
			gdShouyi.setFundsNum("" + num);
			// gdShouyi.setOwnMoney(String.valueOf(allMoney));
			gdShouyi.setFundsAllMoney(String.valueOf(gdAllMoney));
			gdShouyi.setFundsLjProfit(String.valueOf(gdljProfit));
		} else {
		}
		RedisCilent.setString("ALLASSETS_gudingProduct" + user.getId(),
				allGdShouyiObj.toString(), 1000);
	}

	/* 查询盈米宝（华康宝）信息 */
	private void getYMB(SysUser user, AllAssetsRes ymb) {
		// Path：/trade/getWalletShares
		BigDecimal allMoney = new BigDecimal(0);
		Map<String, String> params = new HashMap<>();
		params.put("brokerUserId", user.getName());// PayMentMethodCtrl
		params.put("accountId", user.getAccountId());
		String fundsList = utils.get("/trade/getWalletShares", params);
		if (!fundsList.contains("msg")) {
			RedisCilent.setString("ALLASSETS_yingmibao" + user.getId(),
					fundsList, 1000);
			JSONArray resultArray = new JSONArray(fundsList);
			BigDecimal totalMoney = new BigDecimal(0);
			BigDecimal ljsy = new BigDecimal(0);// 盈米宝累计收益
			BigDecimal zxsy = new BigDecimal(0);// 最新收益
			for (int i = 0; i < resultArray.length(); i++) {
				JSONObject obj = resultArray.getJSONObject(i);
				BigDecimal currentShare = new BigDecimal(obj.get(
						"totalAvailShare").toString());
				BigDecimal jz = new BigDecimal(0);
				HqlFilter fundHqlFilter = new HqlFilter();
				String fundCode = obj.getString("fundCode");
				fundHqlFilter.addEQFilter("fundCode", fundCode);

				String ljShouyi = qryLeijiShouyi(user, fundCode);
				if ((!"{}".equals(ljShouyi)) && (!ljShouyi.contains("msg"))) {
					JSONObject objJsonObject = new JSONObject(ljShouyi);
					JSONArray oneForLj = objJsonObject.getJSONArray(fundCode);
					for (int y = 0; y < oneForLj.length(); y++) {
						JSONObject nn = oneForLj.getJSONObject(y);

						BigDecimal profit = new BigDecimal(nn.get("profit")
								.toString());

						ljsy = ljsy.add(profit);
					}

					String zxShouyi = qryDayShouyi(user, fundCode);
					JSONObject zxJsonObject = new JSONObject(zxShouyi);
					JSONArray oneForzx = zxJsonObject.getJSONArray(fundCode);
					for (int y = 0; y < oneForzx.length(); y++) {
						JSONObject mm = oneForzx.getJSONObject(y);

						BigDecimal profit = new BigDecimal(mm.get("profit")
								.toString());
						zxsy = zxsy.add(profit);
					}

					List<FundNav> fundList = fundNavService
							.findByFilter(fundHqlFilter);// 获取基金净值。
					if (fundList.size() > 0) {
						jz = fundList.get(0).getNav();
					}
					totalMoney = totalMoney.add(currentShare.multiply(jz));// 份额*最新净值
				}

			}
			allMoney = allMoney.add(totalMoney);
			ymb.setFundsName("华康宝");
			ymb.setFundsNum(String.valueOf(resultArray.length()));// ??????????????????????????????
			ymb.setFundsAllMoney(String.valueOf(totalMoney));
			ymb.setFundsLjProfit(String.valueOf(ljsy));
			ymb.setNewProfit(String.valueOf(zxsy));
			// ymb.setOwnMoney(String.valueOf(allMoney));
		} else {
			ymb.setFundsName("华康宝信息获取错误");
		}
	}

	/* 查询产品名称 */
	private String qryProductName(Long productId, int companyId) {
		String steString = "";
		HqlFilter productFilter = new HqlFilter();
		productFilter.addEQFilter("Id", productId);
		// productFilter.addEQFilter("companyId", companyId);
		List<ProductInfo> prlistInfos = productInfoService
				.findByFilter(productFilter);
		if (prlistInfos.size() > 0) {
			ProductInfo productInfo = prlistInfos.get(0);
			return productInfo.getName();
		}
		return steString;
	}

	/* 查询客户在盈米的基金 */
	private void getymFunds(SysUser user, AllAssetsRes jjLicai) {
		Map<String, String> params = new HashMap<>();
		params.put("brokerUserId", user.getName());// PayMentMethodCtrl
		params.put("accountId", user.getAccountId());
		String fundsList = utils.get("/trade/getFundShares", params);
		BigDecimal allMoney =   BigDecimal.valueOf(0);
		BigDecimal yestDayProfit = BigDecimal.valueOf(0);
		BigDecimal allProfit = BigDecimal.valueOf(0);
		if (!fundsList.contains("msg")) {
			JSONArray resultArray = new JSONArray(fundsList);
			BigDecimal jjLicaiAllMoney = BigDecimal.valueOf(0);
			JSONArray yingmiFundsList = new JSONArray();
			for (int i = 0; i < resultArray.length(); i++) {
				JSONObject objectStr = resultArray.getJSONObject(i);
				try {
					BigDecimal totalShare = new BigDecimal(objectStr.get(
							"totalShare").toString());// 获取总份额
					String nav = objectStr.get("nav").toString();
					String navDate = objectStr.get("navDate").toString();
					String previousProfit = objectStr.get("previousProfit")
							.toString();
					String accumulatedProfit = objectStr.get(
							"accumulatedProfit").toString();
					objectStr.put("jingzhi", nav);
					objectStr.put("jingzhiDate", navDate);
					objectStr.put("dayProfit", previousProfit);
					objectStr.put("leijiProfit", accumulatedProfit);
					yestDayProfit = yestDayProfit.add(new BigDecimal(
							previousProfit));
					allProfit = allProfit
							.add(new BigDecimal(accumulatedProfit));
					yingmiFundsList.put(objectStr);
					allMoney = allMoney.add(new BigDecimal(nav)
							.multiply(totalShare));
					jjLicaiAllMoney = jjLicaiAllMoney.add(new BigDecimal(nav)
							.multiply(totalShare));
				} catch (Exception e) {
					logger.error("查询客户在盈米的基金异常", e);
				}
			}
			RedisCilent.setString("ALL_ASSETS_yingmiFundsList" + user.getId(),
					yingmiFundsList.toString(), 1000);
			jjLicai.setFundsName("基金理财");
			jjLicai.setFundsNum("" + resultArray.length());
			jjLicai.setFundsAllMoney(String.valueOf(jjLicaiAllMoney));
			jjLicai.setFundsLjProfit(String.valueOf(allProfit));
			jjLicai.setNewProfit(String.valueOf(yestDayProfit));
		} else {
			jjLicai.setFundsName("基金理财获取错误");
		}

	}

	/* 累计收益 */
	public String qryLeijiShouyi(SysUser user, String fundCodes) {
		// /盈亏查询trade/getProfits
		Map<String, String> params = new HashMap<>();
		params.put("brokerUserId", user.getName());// PayMentMethodCtrl
		params.put("accountId", user.getAccountId());
		// if (StringHelper.isEmpty(user.getAccountId())) {
		// logger.info("qryLeijiShouyi()--accountId为空");
		// }
		params.put("beginDate", "2016-01-01");
		Calendar calendar = Calendar.getInstance();
		String endDate = calendar.get(Calendar.YEAR)
				+ "-"
				+ ((calendar.get(Calendar.MONTH) + 1) > 9 ? (calendar
						.get(Calendar.MONTH) + 1) : ("0" + (calendar
						.get(Calendar.MONTH) + 1))) + "-"
				+ calendar.get(Calendar.DAY_OF_MONTH);
		params.put("endDate", endDate);
		if (!StringHelper.isEmpty(fundCodes)) {
			params.put("fundCode", fundCodes);
		}
		String shouyi = utils.get("/trade/getProfits", params);
		return shouyi;
	}

	/* 当日（昨日）收益 */
	public String qryDayShouyi(SysUser user, String fundCodes) {
		// /盈亏查询trade/getProfits 000379,000380,000978,001666,392001 13556806196
		// 5fgvkeu8b96c
		Map<String, String> params = new HashMap<>();
		params.put("brokerUserId", user.getName());// PayMentMethodCtrl
		params.put("accountId", user.getAccountId());
		if (!StringHelper.isEmpty(fundCodes)) {
			params.put("fundCode", fundCodes);
		}
		String shouyi = utils.get("/trade/getProfits", params);
		return shouyi;
	}

	/* 收益添加到obj中 */
	private void objAddShouyi(JSONArray fundsList, String dayProfit,
			String ljProfit, List<AllAssetsRes> assetsDetail) {

		BigDecimal shouyeShouyi = new BigDecimal(0);
		BigDecimal shouyeDayShouyi = new BigDecimal(0);
		for (int i = 0; i < fundsList.length(); i++) {
			JSONObject obj = fundsList.getJSONObject(i);
			BigDecimal oneFundDayAllPro = new BigDecimal(0);
			BigDecimal oneFundljPro = new BigDecimal(0);
			if (!"{}".equals(dayProfit)) {
				JSONObject dayPro = new JSONObject(dayProfit);
				JSONArray oneFundDayList = new JSONArray(dayPro.get(
						obj.get("fundCode").toString()).toString());
				for (int j = 0; j < oneFundDayList.length(); j++) {
					oneFundDayAllPro = oneFundDayAllPro.add(new BigDecimal(
							oneFundDayList.getJSONObject(j).get("profit")
									.toString()));
					obj.put("dayProfit", oneFundDayAllPro);
				}
			}
			if (!"{}".equals(ljProfit)) {
				JSONObject leijiPro = new JSONObject(ljProfit);
				JSONArray oneFundAllList = new JSONArray(leijiPro.get(
						obj.get("fundCode").toString()).toString());
				for (int k = 0; k < oneFundAllList.length(); k++) {
					oneFundljPro = oneFundljPro.add(new BigDecimal(
							oneFundAllList.getJSONObject(k).get("profit")
									.toString()));
					obj.put("leijiProfit", oneFundljPro);
				}
			}

			shouyeDayShouyi = shouyeDayShouyi.add(oneFundDayAllPro);
			shouyeShouyi = shouyeShouyi.add(oneFundljPro);
		}

		for (int p = 0; p < assetsDetail.size(); p++) {
			AllAssetsRes oo = assetsDetail.get(p);
			if ("基金理财".equals(oo.getFundsName())) {
				/*************************************************************************/
				// oo.
				oo.setFundsLjProfit(String.valueOf(shouyeShouyi));
				oo.setNewProfit(String.valueOf(shouyeDayShouyi));
			}
		}
	}

	@ResponseBody
	@RequestMapping(value = "/qryYmiFunds", produces = "application/json;charset=UTF8", method = RequestMethod.GET)
	public ResponseBase<List<AllAssetsRes>> qryYmiFunds(
			@RequestParam String userId) {// @RequestParam
		// String accountId
		userId = userId.split(",")[0];
		ResponseBase<List<AllAssetsRes>> rBase = new ResponseBase<List<AllAssetsRes>>();
		if (!StringHelper.isEmpty(RedisCilent
				.getString("ALL_ASSETS_yingmiFundsList" + userId))) {
			List<AllAssetsRes> resultList = new ArrayList<AllAssetsRes>();
			// System.out.println(RedisCilent
			// .getString("ALL_ASSETS_yingmiFundsList"));
			JSONArray arr = new JSONArray(
					RedisCilent
							.getString("ALL_ASSETS_yingmiFundsList" + userId));
			for (int i = 0; i < arr.length(); i++) {
				JSONObject object = arr.getJSONObject(i);
				AllAssetsRes allAssetsRes = new AllAssetsRes();
				allAssetsRes.setAccountId(object.get("accountId").toString());
				allAssetsRes.setJingzhi(object.get("jingzhi").toString());
				allAssetsRes.setFundCode(object.get("fundCode").toString());
				allAssetsRes.setPaymentMethodId(object.get("paymentMethodId")
						.toString());
				allAssetsRes.setAvaiShare(object.get("avaiShare").toString());
				allAssetsRes.setDividendMethod(object.get("dividendMethod")
						.toString());
				allAssetsRes.setFundName(object.getString("fundName"));
				allAssetsRes.setLeijiProfit(object.get("leijiProfit")
						.toString());
				allAssetsRes.setShareType(object.get("shareType").toString());
				allAssetsRes.setDayProfit(object.get("dayProfit").toString());
				allAssetsRes.setTotalShare(object.get("totalShare").toString());
				allAssetsRes.setJingzhiDate(object.get("jingzhiDate")
						.toString());
				allAssetsRes.setShareId(object.get("shareId").toString());

				resultList.add(allAssetsRes);
			}

			rBase.setResult(resultList);
			rBase.setResultCode(ResultCode.SUCC.getCode());
			rBase.setMsg("成功");
		} else {
			rBase.setResult(null);
			rBase.setResultCode(ResultCode.FAILED.getCode());
			rBase.setMsg("查询盈米基金失败");
		}

		return rBase;
	}

	@ResponseBody
	@RequestMapping(value = "/qryYmiWayOrder", produces = "application/json;charset=UTF8", method = RequestMethod.GET)
	public ResponseBase<List<AllAssetsRes>> qryYmiWayOrder(
			@RequestParam String userId) {// @RequestParam
		// String
		// accountId
		userId = userId.split(",")[0];
		ResponseBase<List<AllAssetsRes>> rBase = new ResponseBase<List<AllAssetsRes>>();
		if (!StringHelper.isEmpty(RedisCilent.getString("ALLASSETS_wayOrderStr"
				+ userId))) {
			List<AllAssetsRes> resultList = new ArrayList<AllAssetsRes>();
			JSONArray arr = new JSONArray(
					RedisCilent.getString("ALLASSETS_wayOrderStr" + userId));
			for (int i = 0; i < arr.length(); i++) {
				JSONObject object = arr.getJSONObject(i);
				AllAssetsRes allAssetsRes = new AllAssetsRes();
				allAssetsRes.setPaymentMethodId(object.get("paymentMethodId")
						.toString());
				allAssetsRes.setWalletId(object.get("walletId").toString());
				allAssetsRes.setFundOrderCode(object.get("fundOrderCode")
						.toString());
				allAssetsRes.setFundCode(object.get("fundCode").toString());
				allAssetsRes.setShareType(object.get("shareType").toString());
				allAssetsRes.setOrderCreatedOn(object.get("orderCreatedOn")
						.toString());
				allAssetsRes.setTradeAmount(object.get("tradeAmount")
						.toString());
				allAssetsRes.setSuccessAmount(object.get("successAmount")
						.toString());
				allAssetsRes.setSuccessShare(object.get("successShare")
						.toString());
				allAssetsRes.setFundName(object.getString("fundName"));
				resultList.add(allAssetsRes);
			}

			rBase.setResult(resultList);
			rBase.setResultCode(ResultCode.SUCC.getCode());
			rBase.setMsg("成功");
		} else {
			rBase.setResult(null);
			rBase.setResultCode(ResultCode.FAILED.getCode());
			rBase.setMsg("查询在途订单失败");
		}
		return rBase;
	}

	@ResponseBody
	@RequestMapping(value = "/qryYingmiBao", produces = "application/json;charset=UTF8", method = RequestMethod.GET)
	public ResponseBase<List<AllAssetsRes>> qryYingmiBao(
			@RequestParam String userId) {// @RequestParam String accountId
		userId = userId.split(",")[0];
		ResponseBase<List<AllAssetsRes>> rBase = new ResponseBase<List<AllAssetsRes>>();

		if (!StringHelper.isEmpty(RedisCilent.getString("ALLASSETS_yingmibao"
				+ userId))) {
			JSONArray ymbArray = new JSONArray(
					RedisCilent.getString("ALLASSETS_yingmibao" + userId));
			List<AllAssetsRes> resList = new ArrayList<AllAssetsRes>();
			if (qryUser(userId).size() > 0) {
				SysUser iSysUser = qryUser(userId).get(0);
				for (int i = 0; i < ymbArray.length(); i++) {
					JSONObject object = ymbArray.getJSONObject(i);
					AllAssetsRes allAssetsRes = new AllAssetsRes();
					allAssetsRes.setWalletId(object.get("walletId").toString());
					allAssetsRes.setFundCode(object.get("fundCode").toString());
					allAssetsRes.setFundName(object.getString("fundName"));
					allAssetsRes.setPaymentMethodId(object.get(
							"paymentMethodId").toString());
					allAssetsRes.setTotalAvailShare(object.get(
							"totalAvailShare").toString());
					BigDecimal totalShare = new BigDecimal(object.get(
							"totalAvailShare").toString());
					String fundCode = object.get("fundCode").toString();
					FundNav jijin = qryjingzhi(fundCode);
					allAssetsRes.setJingzhi(jijin.getNav().toString());
					object.put("yue", totalShare.multiply(jijin.getNav()));
					allAssetsRes.setYue(totalShare.multiply(jijin.getNav())
							.toString());
					allAssetsRes.setWanfenShouyi(jijin.getUnitYield()
							.toString());
					allAssetsRes
							.setQiriNianhua(jijin.getYearlyRoe().toString());
					String dayShouyi = qryDayShouyi(iSysUser, fundCode);
					JSONObject uiJsonObject = new JSONObject(dayShouyi);
					JSONArray uiArray = uiJsonObject.getJSONArray(fundCode);
					BigDecimal obProfit = new BigDecimal("0");
					BigDecimal allProfitt = new BigDecimal("0");
					for (int u = 0; u < uiArray.length(); u++) {
						BigDecimal dayProfit = new BigDecimal(uiArray
								.getJSONObject(u).get("profit").toString());
						obProfit = obProfit.add(dayProfit);
					}

					// object.put("dayProfit", obProfit);
					allAssetsRes.setDayProfit(obProfit.toString());
					String leijiShouyi = qryLeijiShouyi(iSysUser, fundCode);
					uiJsonObject = new JSONObject(leijiShouyi);
					uiArray = uiJsonObject.getJSONArray(fundCode);
					for (int u = 0; u < uiArray.length(); u++) {
						BigDecimal ddProfit = new BigDecimal(uiArray
								.getJSONObject(u).get("profit").toString());
						allProfitt = allProfitt.add(ddProfit);
					}
					// object.put("ljProfit", allProfitt);
					allAssetsRes.setLjProfit(allProfitt.toString());
					resList.add(allAssetsRes);
				}
				rBase.setResult(resList);
				rBase.setResultCode(ResultCode.SUCC.getCode());
				rBase.setMsg("成功");
			} else {
				rBase.setResult(null);
				rBase.setResultCode(ResultCode.FAILED.getCode());
				rBase.setMsg("客户查询失败");
			}
		} else {
			rBase.setResultCode(ResultCode.FAILED.getCode());
			rBase.setMsg("查询盈米宝失败");
			rBase.setResult(null);
		}

		return rBase;
	}

	@ResponseBody
	@RequestMapping(value = "/qryGuDingShouyi", produces = "application/json;charset=UTF8", method = RequestMethod.GET)
	public ResponseBase<List<AllAssetsRes>> qryGuDingShouyi(
			@RequestParam String userId) {// @RequestParam
		// String
		// accountId
		userId = userId.split(",")[0];
		ResponseBase<List<AllAssetsRes>> rBase = new ResponseBase<List<AllAssetsRes>>();

		if (!StringHelper.isEmpty(RedisCilent
				.getString("ALLASSETS_gudingProduct" + userId))) {

			List<AllAssetsRes> resultList = new ArrayList<AllAssetsRes>();
			// System.out
			// .println(RedisCilent.getString("ALLASSETS_gudingProduct"));
			JSONArray arr = new JSONArray(
					RedisCilent.getString("ALLASSETS_gudingProduct" + userId));

			for (int i = 0; i < arr.length(); i++) {
				JSONObject object = arr.getJSONObject(i);
				AllAssetsRes allAssetsRes = new AllAssetsRes();
				allAssetsRes.setHcOurdate(object.get("date").toString());
				allAssetsRes.setHcOurtouziAmout(object.get("touziAmout")
						.toString());
				allAssetsRes.setHcOurProductName(object.get("ProductName")
						.toString());
				allAssetsRes.setHcOuryuqiShouyi(object.get("yuqiShouyi")
						.toString());
				resultList.add(allAssetsRes);
			}

			rBase.setResult(resultList);
			rBase.setResultCode(ResultCode.SUCC.getCode());
			rBase.setMsg("成功");
		} else {
			rBase.setResult(null);
			rBase.setResultCode(ResultCode.FAILED.getCode());
			rBase.setMsg("查询火柴和自有产品失败");
		}
		return rBase;
	}

	private List<SysUser> qryUser(String userId) {
		List<SysUser> userList = null;
		HqlFilter sysHqlFilter = new HqlFilter();
		sysHqlFilter.addEQFilter("Id", userId);
		userList = sysUserService.findByFilter(sysHqlFilter);
		return userList;
	}

	private FundNav qryjingzhi(String fundCode) {
		FundNav aFundNav = new FundNav();
		HqlFilter fundHqlFilter = new HqlFilter();
		fundHqlFilter.addEQFilter("fundCode", fundCode);
		List<FundNav> fundList = fundNavService.findByFilter(fundHqlFilter);// 获取基金净值。
		if (fundList.size() > 0) {
			aFundNav = fundList.get(0);
		}
		return aFundNav;
	}

	//
	// Date date=new Date(createDate);
	// Calendar cal=Calendar.getInstance();
	// cal.setTime(date);
	// String
	// orderdate=""+cal.get(Calendar.YEAR)+cal.get(Calendar.MONTH)+cal.get(Calendar.DAY_OF_MONTH);
	// Calendar nowDate=Calendar.getInstance();
	// String
	// nowString=""+nowDate.get(Calendar.YEAR)+nowDate.get(Calendar.MONTH)+nowDate.get(Calendar.DAY_OF_MONTH);
	// if(nowString.equals(orderdate)){//今日新增订单

	// if(!(object.get("successAmount").toString()).equals("null")){
	// BigDecimal
	// orderMoney=BigDecimal.valueOf((double)object.get("successAmount"));
	// allMoney=allMoney.add(orderMoney);
	// }

	// }
	@ResponseBody
	@RequestMapping(value = "/qryDayAllProfits", produces = "application/json;charset=UTF8", method = RequestMethod.GET)
	public ResponseBase<String> qryDayAllProfits(@RequestParam String accountId) {

		ResponseBase<String> rb = new ResponseBase<String>();
		float allProfits = 0.0f;

		HqlFilter sysHqlFilter = new HqlFilter();
		sysHqlFilter.addEQFilter("accountId", accountId);
		SysUser sysUser = null;
		List<SysUser> slist = sysUserService.findByFilter(sysHqlFilter);
		if (slist.size() > 0) {
			sysUser = slist.get(0);
			Map<String, String> params = new HashMap<>();
			params.put("brokerUserId", sysUser.getName());// PayMentMethodCtrl
			params.put("accountId", sysUser.getAccountId());
			String result = utils.get("/trade/getProfits", params);
			JSONObject jsonMap = new JSONObject(result);
			Iterator<String> it = jsonMap.keys();
			while (it.hasNext()) {
				String key = (String) it.next();
				JSONArray array = new JSONArray(jsonMap.get(key).toString());
				for (int i = 0; i < array.length(); i++) {
					String str = array.getString(i);
					ObjectMapper objectMapper = new ObjectMapper();
					try {
						YingmiDayProfit yingmiDayProfit = (YingmiDayProfit) objectMapper
								.readValue(str, YingmiDayProfit.class);
						allProfits += Float.parseFloat(yingmiDayProfit
								.getProfit());
					} catch (Exception e) {
						logger.error("查询总收益异常", e);
					}
				}

			}

			/*---------------------------------------盈米查询结束,自有产品及火柴查询开始-----------------------------------*/

			HqlFilter routeHqlFilter = new HqlFilter();
			routeHqlFilter.addEQFilter("accountId", sysUser.getAccountId());

			List<OrderRouteInfo> userOrderRouteList = orderRouteInfoService
					.findByFilter(routeHqlFilter);
			if (userOrderRouteList.size() > 0) {
				for (OrderRouteInfo orderRouteInfo : userOrderRouteList) {
					Long orderId = orderRouteInfo.getOrderId();
					HqlFilter orderInfoHqlFilter = new HqlFilter();
					routeHqlFilter.addEQFilter("id", orderId);
					List<OrderInfo> orderInfoList = orderInfoService
							.findByFilter(orderInfoHqlFilter);
					for (OrderInfo orderInfo : orderInfoList) {
						Long orderConfirmDate = orderInfo.getOrderConfirmDate();
						Long dividendDate = orderInfo.getDividendDate();// 还本付息时间
						Long dateBetween = new Date().getTime()
								- orderConfirmDate;
						if (dateBetween <= dividendDate) {// 未到期，取预期收益
							allProfits += orderInfo.getDividend().floatValue();
						}
					}
				}
			}
			rb.setMsg("成功");
			rb.setResult(String.valueOf(allProfits));
			rb.setResultCode(ResultCode.SUCC.getCode());
		} else {
			rb.setMsg("失败");
			rb.setResult(null);
			rb.setResultCode(ResultCode.FAILED.getCode());
		}

		return rb;

	}

}
